package com.lg.zk.server;

import lombok.extern.slf4j.Slf4j;
import org.apache.zookeeper.*;

import java.io.IOException;

/**
 * 注册服务server
 *
 * @author by Mr. Li 2020/12/10 12:56
 */
@Slf4j
public class DistributeServer {
    private String connectString = "192.168.31.201:2181,192.168.31.201:2182,192.168.31.201:2183,192.168.31.201:2184,192.168.31.201:2185";
    private int sessionTimeout = 2000;
    private ZooKeeper zkClient = null;
    private String parentNode = "/servers";

    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        DistributeServer server = new DistributeServer();
        // 1. 连接zookeeper集群
        server.getConnect();
        // 2. 注册节点
        server.registServer("gulimall");
        // 3. 业务逻辑处理
        server.business("gulimall");
    }

    /**
     * 业务代码
     *
     * @param hostname
     */
    private void business(String hostname) throws InterruptedException {
        System.out.println(hostname+" is working ...");
        Thread.sleep(Long.MAX_VALUE);
    }

    /**
     * 获取zk连接
     */
    private void getConnect() throws IOException {
        zkClient = new ZooKeeper(connectString, sessionTimeout, event -> {

        });

    }

    /**
     * 注册服务器
     *
     * @param hostname 服务名
     */
    public void registServer(String hostname) throws KeeperException, InterruptedException {
        String create = zkClient.create(parentNode + "/server", hostname.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL);
        //System.out.println(hostname + " is online " + create);
        log.info(hostname + " is online " + create);
    }

}
